import React, { useState, useEffect, useRef } from 'react';
import { 
  Button, 
  message, 
  Modal, 
  Table, 
  Space, 
  Input, 
  Form, 
  InputNumber,
  DatePicker
} from 'antd';
import { 
  PlusOutlined, 
  DeleteOutlined, 
  EditOutlined,
  UploadOutlined
} from '@ant-design/icons';
import { 
  getDetectionPointList, 
  createDetectionPoint, 
  updateDetectionPoint, 
  deleteDetectionPoint, 
  DetectionPointItem 
} from '../../api/gis';
import dayjs from 'dayjs';
import DetectionPointBatchUploadModal from './DetectionPointBatchUploadModal';

interface DetectionPointManagementProps {
  planetId: number;
}

const DetectionPointManagement: React.FC<DetectionPointManagementProps> = ({ planetId }) => {
  // 探测点管理相关状态
  const [detectionPoints, setDetectionPoints] = useState<DetectionPointItem[]>([]);
  const [detectionPointLoading, setDetectionPointLoading] = useState(false);
  const [detectionPointModalVisible, setDetectionPointModalVisible] = useState(false);
  const [editingDetectionPoint, setEditingDetectionPoint] = useState<DetectionPointItem | null>(null);
  const [selectedDetectionPointKeys, setSelectedDetectionPointKeys] = useState<React.Key[]>([]);
  const [batchDeleteLoading, setBatchDeleteLoading] = useState(false);
  const [detectionPointForm] = Form.useForm();
  const [detectionPointFilterForm] = Form.useForm();
  
  // 批量上传相关状态
  const [batchUploadModalVisible, setBatchUploadModalVisible] = useState(false);
  
  // 分页状态
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);

  // 表格容器ref和滚动高度
  const tableContainerRef = useRef(null);
  const [tableScrollY, setTableScrollY] = useState(0);

  // 计算表格滚动高度
  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      // 获取整个页面的可用高度
      const pageHeight = window.innerHeight;
      // 减去面包屑、tabs头部、筛选表单、操作按钮等的高度
      const breadcrumbHeight = 48; // 面包屑高度
      const tabsHeaderHeight = 46; // tabs头部高度
      const filterFormHeight = 64; // 筛选表单高度
      const actionButtonsHeight = 56; // 操作按钮区域高度
      const padding = 232; // 各种padding和margin
      
      const availableHeight = pageHeight - breadcrumbHeight - tabsHeaderHeight - filterFormHeight - actionButtonsHeight - padding;
      const tableHeaderHeight = 39; // 表格头部高度
      const scrollHeight = Math.max(availableHeight - tableHeaderHeight, 100); // 最小高度100px
      
      setTableScrollY(scrollHeight);
      
      // 直接设置表格容器的高度
      const tableBody = tableContainerRef.current.querySelector('.ant-table-body');
      if (tableBody) {
        tableBody.style.height = scrollHeight + 'px';
        tableBody.style.maxHeight = scrollHeight + 'px';
      }
    }
  };

  useEffect(() => {
    // 延迟计算，确保DOM完全渲染
    const timer = setTimeout(() => {
      calculateTableScrollHeight();
    }, 100);
    
    window.addEventListener('resize', calculateTableScrollHeight);
    return () => {
      clearTimeout(timer);
      window.removeEventListener('resize', calculateTableScrollHeight);
    };
  }, []); // 当组件挂载时计算

  // 获取探测点列表
  const fetchDetectionPoints = async (page = 1, size = 20, filters = {}) => {
    setDetectionPointLoading(true);
    try {
      const formValues = detectionPointFilterForm.getFieldsValue();
      const params: any = {
        planet_id: planetId,
        page,
        page_size: size,
        task: formValues.task || '',
        task_zh: formValues.task_zh || '',
        data_type: formValues.data_type || '',
        data_level: formValues.data_level || '',
        detection_name: formValues.detection_name || '',
        latitude: formValues.latitude || '',
        longitude: formValues.longitude || '',
        ...filters
      };

      // 处理时间范围
      if (formValues.detection_time_range && formValues.detection_time_range.length === 2) {
        params.detection_time__gte = formValues.detection_time_range[0].format('YYYY-MM-DD HH:mm:ss');
        params.detection_time__lte = formValues.detection_time_range[1].format('YYYY-MM-DD HH:mm:ss');
      }

      const response = await getDetectionPointList(params);
      
      if (response.code === 200) {
        setDetectionPoints(response.data.list);
        setTotal(response.data.count);
        setCurrent(response.data.page);
        setPageSize(response.data.page_size);
      } else {
        message.error(response.msg || '获取探测点列表失败');
      }
    } catch (error) {
      console.error('获取探测点列表失败:', error);
      message.error(error?.message || '获取探测点列表失败');
    } finally {
      setDetectionPointLoading(false);
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    fetchDetectionPoints();
  }, [planetId]);

  // 筛选表单提交
  const onDetectionPointFilterFinish = () => {
    setCurrent(1);
    fetchDetectionPoints(1, pageSize);
  };

  // 分页处理
  const handleDetectionPointTableChange = (paginationInfo: any) => {
    setCurrent(paginationInfo.current);
    setPageSize(paginationInfo.pageSize);
    fetchDetectionPoints(paginationInfo.current, paginationInfo.pageSize);
  };

  // 新建探测点
  const handleCreateDetectionPoint = () => {
    setEditingDetectionPoint(null);
    detectionPointForm.resetFields();
    setDetectionPointModalVisible(true);
  };

  // 编辑探测点
  const handleEditDetectionPoint = (record: DetectionPointItem) => {
    setEditingDetectionPoint(record);
    detectionPointForm.setFieldsValue({
      detection_time: dayjs(record.detection_time),
      task: record.task,
      task_zh: record.task_zh,
      data_type: record.data_type,
      data_level: record.data_level,
      detection_name: record.detection_name,
      latitude: record.latitude,
      longitude: record.longitude,
      files: record.files
    });
    setDetectionPointModalVisible(true);
  };

  // 删除探测点
  const handleDeleteDetectionPoint = async (record: DetectionPointItem) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除探测点 "${record.detection_name}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await deleteDetectionPoint({ id_list: [record.id] });
          if (response.code === 200) {
            message.success('删除成功');
            fetchDetectionPoints(current, pageSize);
          } else {
            message.error(response.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除探测点失败:', error);
          message.error(error?.message || '删除失败');
        }
      }
    });
  };

  // 批量删除探测点
  const handleBatchDeleteDetectionPoint = () => {
    if (selectedDetectionPointKeys.length === 0) {
      message.warning('请选择要删除的探测点');
      return;
    }
    Modal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedDetectionPointKeys.length} 个探测点吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        setBatchDeleteLoading(true);
        try {
          const response = await deleteDetectionPoint({ id_list: selectedDetectionPointKeys.map(id => Number(id)) });
          if (response.code === 200) {
            message.success('批量删除成功');
            setSelectedDetectionPointKeys([]);
            fetchDetectionPoints(current, pageSize);
          } else {
            message.error(response.msg || '批量删除失败');
          }
        } catch (error) {
          console.error('批量删除失败:', error);
          message.error(error?.message || '批量删除失败');
        } finally {
          setBatchDeleteLoading(false);
        }
      }
    });
  };

  // 保存探测点（新建或编辑）
  const handleSaveDetectionPoint = async () => {
    try {
      const values = await detectionPointForm.validateFields();
      
      // 处理探测时间
      const detectionTime = values.detection_time.format('YYYY-MM-DD HH:mm:ss');
      
      // 从values中移除detection_time，避免被覆盖
      const { detection_time, ...otherValues } = values;
      
      if (editingDetectionPoint) {
        // 编辑
        const response = await updateDetectionPoint({
          id: editingDetectionPoint.id,
          planet_id: planetId,
          detection_time: detectionTime,
          ...otherValues
        });
        if (response.code === 200) {
          message.success('修改成功');
          setDetectionPointModalVisible(false);
          fetchDetectionPoints(current, pageSize);
        } else {
          message.error(response.msg || '修改失败');
        }
      } else {
        // 新建
        const response = await createDetectionPoint({
          planet_id: planetId,
          detection_time: detectionTime,
          ...otherValues
        });
        if (response.code === 200) {
          message.success('创建成功');
          setDetectionPointModalVisible(false);
          fetchDetectionPoints(current, pageSize);
        } else {
          message.error(response.msg || '创建失败');
        }
      }
    } catch (error) {
      console.error('保存探测点失败:', error);
      message.error(error?.message || '保存失败');
    }
  };

  // 批量上传成功回调
  const handleBatchUploadSuccess = () => {
    fetchDetectionPoints(current, pageSize);
  };

  // 表格选择配置
  const detectionPointRowSelection = {
    selectedRowKeys: selectedDetectionPointKeys,
    columnWidth: 50,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedDetectionPointKeys(newSelectedRowKeys);
    }
  };

  // 探测点表格列定义
  const detectionPointColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      ellipsis: true,
    },
    {
      title: '探测时间',
      dataIndex: 'detection_time',
      key: 'detection_time',
      width: 180,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '任务',
      dataIndex: 'task',
      key: 'task',
      width: 120,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '任务中文',
      dataIndex: 'task_zh',
      key: 'task_zh',
      width: 120,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '数据类型',
      dataIndex: 'data_type',
      key: 'data_type',
      width: 120,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '数据级别',
      dataIndex: 'data_level',
      key: 'data_level',
      width: 120,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '纬度',
      dataIndex: 'latitude',
      key: 'latitude',
      width: 120,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '经度',
      dataIndex: 'longitude',
      key: 'longitude',
      width: 120,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '文件路径',
      dataIndex: 'files',
      key: 'files',
      width: 200,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: 180,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      align: 'center' as const,
      render: (_: any, record: DetectionPointItem) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEditDetectionPoint(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteDetectionPoint(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {/* 筛选表单 */}
      <Form form={detectionPointFilterForm} layout="inline" className="filter-form" onFinish={onDetectionPointFilterFinish} labelCol={{ style: { width: 120 } }}>
        <Form.Item name="detection_num" label="探测点编号" style={{ width: 320 }}>
          <Input placeholder="请输入探测点编号搜索" />
        </Form.Item>
        <Form.Item style={{ paddingLeft: 40 }}>
          <Space>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
            <Button
              htmlType="button"
              onClick={() => {
                detectionPointFilterForm.resetFields();
                fetchDetectionPoints(1, pageSize);
              }}>
              清除
            </Button>
          </Space>
        </Form.Item>
      </Form>

      {/* 操作按钮 */}
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <Button type="primary" danger onClick={handleBatchDeleteDetectionPoint} loading={batchDeleteLoading} disabled={selectedDetectionPointKeys.length === 0}>
            批量删除
          </Button>
        </div>

        <Space>
          <Button 
            type="primary" 
            icon={<UploadOutlined />} 
            onClick={() => setBatchUploadModalVisible(true)}
          >
            批量导入
          </Button>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateDetectionPoint}>
            新建探测点
          </Button>
        </Space>
      </div>

      {/* 数据表格 */}
      <div className="pds-table-container" ref={tableContainerRef}>
        <Table
          rowSelection={detectionPointRowSelection}
          columns={detectionPointColumns}
          dataSource={detectionPoints}
          rowKey="id"
          loading={detectionPointLoading}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            onChange: (page, size) => {
              setCurrent(page);
              setPageSize(size);
            },
            showTotal: (total) => `共 ${total} 条`
          }}
          scroll={{ y: tableScrollY, x: 'max-content' }}
          bordered
          size="small"
          onChange={handleDetectionPointTableChange}
        />
      </div>

      {/* 新建/编辑探测点弹窗 */}
      <Modal
        title={editingDetectionPoint ? '编辑探测点' : '新建探测点'}
        open={detectionPointModalVisible}
        onOk={handleSaveDetectionPoint}
        onCancel={() => setDetectionPointModalVisible(false)}
        width={800}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={detectionPointForm}
          layout="vertical"
          style={{ marginTop: 16 }}
        >
          <div style={{ display: 'flex', gap: 16 }}>
            <div style={{ flex: 1 }}>
              <Form.Item
                name="detection_time"
                label="探测时间"
                rules={[{ required: true, message: '请选择探测时间' }]}
              >
                <DatePicker 
                  showTime 
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择探测时间"
                  style={{ width: '100%' }}
                />
              </Form.Item>
              <Form.Item
                name="task"
                label="任务"
                rules={[{ required: true, message: '请输入任务' }]}
              >
                <Input placeholder="请输入任务" />
              </Form.Item>
              <Form.Item
                name="task_zh"
                label="任务中文"
                rules={[{ required: true, message: '请输入任务中文' }]}
              >
                <Input placeholder="请输入任务中文" />
              </Form.Item>
              <Form.Item
                name="data_type"
                label="数据类型"
                rules={[{ required: true, message: '请输入数据类型' }]}
              >
                <Input placeholder="请输入数据类型" />
              </Form.Item>
              <Form.Item
                name="data_level"
                label="数据级别"
                rules={[{ required: true, message: '请输入数据级别' }]}
              >
                <Input placeholder="请输入数据级别" />
              </Form.Item>
            </div>
            <div style={{ flex: 1 }}>
              <Form.Item
                name="detection_name"
                label="探测点名称"
                rules={[{ required: true, message: '请输入探测点名称' }]}
              >
                <Input placeholder="请输入探测点名称" />
              </Form.Item>
              <Form.Item
                name="latitude"
                label="纬度"
                rules={[{ required: true, message: '请输入纬度' }]}
              >
                <InputNumber placeholder="请输入纬度" style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item
                name="longitude"
                label="经度"
                rules={[{ required: true, message: '请输入经度' }]}
              >
                <InputNumber placeholder="请输入经度" style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item
                name="files"
                label="文件路径"
                rules={[{ required: true, message: '请输入文件路径' }]}
              >
                <Input.TextArea placeholder="请输入文件路径" rows={3} />
              </Form.Item>
            </div>
          </div>
        </Form>
      </Modal>

      {/* 批量上传探测点弹窗 */}
      <DetectionPointBatchUploadModal
        visible={batchUploadModalVisible}
        onCancel={() => setBatchUploadModalVisible(false)}
        planetId={planetId}
        onSuccess={handleBatchUploadSuccess}
      />
    </div>
  );
};

export default DetectionPointManagement; 